import datetime
import json

from django.core.paginator import Paginator
from django.core.serializers import serialize
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from Love_house import settings
from apps.houses.models import House, Area, Facility
from apps.order.models import Order
from utils.views import LoginRequiredJSONMixin


class AreasView(View):
    """城区列表"""

    def get(self, request):
        """提供地址管理界面
        """
        # 获取所有的地址:
        areas = Area.objects.all()
        # 创建空的列表
        data_list = []
        for area in areas:
            data = {
                'aid': area.id,
                'aname': area.name
            }
            data_list.append(data)

        return JsonResponse({"errno": "0", 'errmsg': "获取成功", "data": data_list})


"""
需求：发布新房源，
前端：前端传送title\price\area_id\address\
后端：
    路由：api/v1.0/houses ，post
    步骤：
        1.获取参数--
        2.验证参数
        3.保存信息
        4.返回响应
"""


class NewHousesView(View):
    def post(self, request):
        """发布房源信息"""
        # 1.获取参数
        user = request.user
        data = json.loads(request.body)
        title = data.get('title')  # 标题
        price = data.get('price')  # 单价，单位：分
        area_id = data.get('area_id')  # 归属地的区域编号（外键）
        address = data.get('address')  # 地址
        room_count = data.get('room_count')  # 房间数目
        acreage = data.get('acreage')  # 房屋面积
        unit = data.get('unit')  # 房屋单元， 如几室几厅
        capacity = data.get('capacity')  # 房屋容纳的人数
        beds = data.get('beds')  # 房屋床铺的配置
        deposit = data.get('deposit')  # 房屋押金
        min_days = data.get('min_days')  # 最少入住天数
        max_days = data.get('max_days')  # 最多入住天数，0表示不限制
        facility = data.get('facility')  # 和设施表之间多对多关系
        # 2.验证参数
        if not user.is_authenticated:
            return JsonResponse({'errno': 4101, 'errmsg': '未登录'})
        if not all([title, price, area_id, address, room_count, acreage, unit
                       , capacity, beds, deposit, facility]):
            return JsonResponse({"errno": 4103, "errmsg": "参数不齐全"})
        try:
            area = Area.objects.get(id=area_id)
        except Area.DoesNotExist:
            return JsonResponse({"errno": 4103, "errmsg": "参数有误"})

        # 3.保存信息
        house = House.objects.create(
            user=user,
            area=area,
            title=title,
            price=price,
            address=address,
            room_count=room_count,
            acreage=acreage,
            unit=unit,
            capacity=capacity,
            beds=beds,
            deposit=deposit,
            min_days=min_days,
            max_days=max_days,
        )
        house.facility.set(facility)
        # 4.返回响应
        return JsonResponse({'errno': 0, "errmsg": "发布成功", 'data': {'house_id': house.id}})

    def get(self, request):
        """ 房屋数据搜索 """
        page_size = 8
        redis_expire_time=3600
        # 获取参数
        data = request.GET
        aid = data.get('aid')  # 区域id
        sd = data.get('sd')  # 开始日期
        ed = data.get('ed')  # 结束日期
        sk = data.get('sk')  # 排序方式 booking(订单量），price-inc（低到高），price-des（高到低）
        p = data.get('p')  # 页数，不传默认为1
        # 验证参数

        if aid:
            try:
                Area.objects.get(id=aid)
            except Area.DoesNotExist:
                return JsonResponse({'errno': 4103, 'essmsg': '区域参数有误'})

        # 处理日期数据
        try:
            if sd:
                sd = datetime.datetime.strptime(sd, '%Y-%m-%d')
            if ed:
                ed = datetime.datetime.strptime(ed, '%Y-%m-%d')
            if sd > ed:
                raise sd > ed
        except Exception:
            return JsonResponse({'errno': 4103, 'errmsg': '日期参数有误'})

        # 处理页数
        try:
            p = int(p)
        except Exception:
            p = 1

        #  连接redis
        redis_cli=get_redis_connection('search')
        redis_key = "house_%s_%s_%s_%s" % (sd, ed, aid, sk)
        try:
            # 获取缓存数据
            redis_data = redis_cli.hgetall(redis_key)
        #     b"{'total_page': 3, 'houses': [{'house_id': 13, 'order_count': 0, 'title': '\xe5\x87\xa4\xe5\x87\xb04\xe5\x8f\xb7', 'ctime': datetime.datetime(2020, 10, 23, 7, 10, 9, 227177, tzinfo=<UTC>), 'price': 4000, 'area_name': '\xe4\xb8\x9c\xe5\x9f\x8e\xe5\x8c\xba', 'address': 'adad', 'room_count': 2, 'img_url': 'http://qhzd2cslk.hb-bkt.clouddn.com/Fr1z8-7h7Lw-4JKv8eAmzuHKeZNV', 'user_avatar': 'http://qhzd2cslk.hb-bkt.clouddn.com/FhQTUJPJYXxCS2ZIyUMhl2tyAI3r'}]}"
        except Exception :
            pass
        else:
            if redis_data:
                for page,data_bytes in redis_data.items():
                    if int(page)==p:
                        data_str1 = data_bytes.decode()
                        data_str2 = data_str1.replace("\'", '\"')
                        # {"total_page": 3, "houses": [{"house_id": 13, "order_count": 0, "title": "凤凰4号", "ctime": "2020-10-23", "price": 4000, "area_name": "东城区", "address": "adad", "room_count": 2, "img_url": "http://qhzd2cslk.hb-bkt.clouddn.com/Fr1z8-7h7Lw-4JKv8eAmzuHKeZNV", "user_avatar": "http://qhzd2cslk.hb-bkt.clouddn.com/FhQTUJPJYXxCS2ZIyUMhl2tyAI3r"}]}
                        data =json.loads(data_str2)

                    else:
                        return JsonResponse({'errno': 4500, 'errmsg': '缓存数据查询异常'})

            else:

                # 填充过滤条件
                # 时间条件
                conflict_orders = None

                try:
                    if sd and ed:
                        # 查询冲突的订单
                        conflict_orders = Order.objects.filter(begin_date__lte=ed, end_date__gte=sd)
                    elif sd:
                        # 查询冲突的订单：
                        conflict_orders = Order.objects.filter(end_date__gte=sd)
                    elif ed:
                        conflict_orders = Order.objects.filter(begin_date__lte=ed)
                except Exception:
                    return JsonResponse({'errno': 4001, 'errmsg': '数据库异常'})

                # 日期冲突房源id
                conflict_house_ids = []
                if conflict_orders:
                    # 从订单中获取日期冲突的房子 id
                    for order in conflict_orders:
                        conflict_house_ids.append(order.house_id)

                if aid:
                    area = Area.objects.get(id=aid)
                    # 排序过滤条件查询房源
                    if sk == 'booking':  # 入住最多
                        houses_obj = House.objects.filter(area=area).exclude(id__in=conflict_house_ids).order_by('-order_count')
                    elif sk == 'price-inc':  # 价格低到高
                        houses_obj = House.objects.filter(area=area).exclude(id__in=conflict_house_ids).order_by('price')
                    elif sk == 'price-des':  # 价格低到高
                        houses_obj = House.objects.filter(area=area).exclude(id__in=conflict_house_ids).order_by('-price')
                    else:
                        houses_obj = House.objects.filter(area=area).exclude(id__in=conflict_house_ids).order_by('-create_time')
                else:
                    # 排序过滤条件查询房源
                    if sk == 'booking':  # 入住最多
                        houses_obj = House.objects.exclude(id__in=conflict_house_ids).order_by('-order_count')
                    elif sk == 'price-inc':  # 价格低到高
                        houses_obj = House.objects.exclude(id__in=conflict_house_ids).order_by('price')
                    elif sk == 'price-des':  # 价格低到高
                        houses_obj = House.objects.exclude(id__in=conflict_house_ids).order_by('-price')
                    else:
                        houses_obj = House.objects.exclude(id__in=conflict_house_ids).order_by('-create_time')

                # 处理分页
                paginator = Paginator(houses_obj, page_size)
                try:
                    houses_list = paginator.page(p)
                except Exception:
                    return JsonResponse({'code': 4004,
                                         'errmsg': '数据出错'})

                # 获取列表页总页数
                total_page = paginator.num_pages
                houses = []
                for house in houses_list:
                    houses.append({
                        "house_id": house.id,
                        "order_count": house.order_count,
                        "title": house.title,
                        "ctime": datetime.datetime.strftime(house.create_time, '%Y-%m-%d'),
                        "price": house.price,
                        "area_name": house.area.name,
                        "address": house.address,
                        "room_count": house.room_count,
                        "img_url": QINIU_DOMIN_PREFIX + str(house.index_image_url),
                        "user_avatar": QINIU_DOMIN_PREFIX + str(house.user.avatar)
                    })

                data = {"total_page": total_page, "houses": houses}

                if p <= total_page:

                    # 哈希类型
                    try:
                        pipeline = redis_cli.pipeline()
                        for house in houses:
                            # 设置缓存数据
                            redis_key = "house_%s_%s_%s_%s" % (sd, ed, aid, sk)
                            pipeline.hset(redis_key,p,str(data))
                            pipeline.expire(redis_key, redis_expire_time)


                        # 执行语句
                        pipeline.execute()
                    except Exception:
                        pass

            return JsonResponse({'errno': 0, 'errmsg': '房屋信息查询成功', 'data': data})


##########################################################################3
#####################################################################################


from django.http import JsonResponse
from django.views import View
# from utils import constants
# from utils import constants
from Love_house.settings import QINIU_DOMIN_PREFIX
from apps.houses.models import House, HouseImage
from utils.image_storage import storage


class Hose_sourse_View(View):
    """上传房源图片"""

    def post(self, request, house_id):
        print(house_id)
        # 1:提取参数
        image_file = request.FILES.get('house_image', None)
        # 2:校验参数
        if image_file is None:
            return JsonResponse({
                "errno": 400,
                "errmsg": "图片没有输入，不能上传"
            }, status=400)

        # 3:数据处理---读取数据(二进制)，上传到七牛云，将返回的地址，保存到数据库
        image_data = image_file.read()

        try:
            file_name = storage(image_data)

        except Exception as e:
            return JsonResponse({
                "errno": 400,
                "errmsg": "图片上传失败"
            })

        try:
            # house = HouseImage.objects.create(house=house_id, url=file_name)
            print(house_id)
            house = House.objects.get(pk=house_id)
            if not house.index_image_url:
                house.index_image_url = file_name
                house.save()
            HouseImage.objects.create(
                house=house,
                url=file_name
            )

        except Exception as e:
            print(e)
            return JsonResponse({
                "errno": 400,
                "errmsg": "图片保存失败"
            })

        url = QINIU_DOMIN_PREFIX + file_name
        # 4：构建响应
        return JsonResponse({
            "data": {
                "url": url
            },
            "errno": "0",
            "errmsg": "图片上传成功",
        })


###############################################################
from apps.houses.models import House


class Hose_list_View(View):
    """我的房屋列表"""

    def get(self, request):
        user = request.user
        houses = House.objects.filter(user_id=user.id).order_by('-create_time')
        house_list = []
        for house in houses:
            data={
                    "address": house.address,
                    "area_name": house.area.name,
                    'ctime': house.create_time,
                    #"ctime": "2017-11-12", #创建时间
                    "house_id":house.id,
                    "img_url":QINIU_DOMIN_PREFIX+str(house.index_image_url), #"http://oyucyko3w.bkt.clouddn.com/FhxrJOpjswkGN2bUgufuXPdXcV6w",
                    "order_count":house.order_count,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                     #"user_avatar": "http://oyucyko3w.bkt.clouddn.com/FmWZRObXNX6TdC8D688AjmDAoVrS"#头像的网址
                    'user_avatar': str(house.user.avatar)
            }
            house_list.append(data)
        data_dict = {"houses": house_list}
        return JsonResponse({"errmsg": "ok", "errno": 0, 'data': data_dict})


#####################################################################################
import random


class Hose_list1_View(View):
    """首页房屋推荐"""

    def get(self, request):
        # user=request.user
        houses = House.objects.all()
        house_list1 = []
        for house in houses:
            data = {
                "house_id": house.id,
                "img_url": QINIU_DOMIN_PREFIX + house.index_image_url,
                # "http://oyucyko3w.bkt.clouddn.com/FhxrJOpjswkGN2bUgufuXPdXcV6w",
                "title": house.title,
            }
            house_list1.append(data)
        house_list = random.sample(house_list1, 5)
        return JsonResponse({"errmsg": "ok", "errno": 0, 'data': house_list})


########################### 房屋详情页面 #########################
class HouseDetailView(View):
    def get(self, request, house_id):
        user = request.user

        #     验证参数
        try:
            house = House.objects.get(id=house_id)
        except House.DoesNotExist:
            return JsonResponse({'errno': 4103, 'errmsg': '参数有误'})

        # 判断是否房主
        if user == house.user:
            user_id = house.user.id
        else:
            user_id = user.id

        # 房屋设备列表
        facility_list = []
        facilities = Facility.objects.filter(house=house)
        for facility in facilities:
            facility_list.append(facility.id)

        # 评论信息
        comments = []
        orders = Order.objects.filter(house=house)
        for order in orders:
            comments.append({

                'comment': order.comment,
                'ctime': datetime.datetime.strftime(order.update_time, '%Y-%m-%d'),
                'user_name': order.user.username

            })

        # 房屋图片列表
        img_urls = []
        img_url = HouseImage.objects.filter(house=house)
        for img in img_url:
            img_urls.append(QINIU_DOMIN_PREFIX + str(img.url))
        from Love_house import settings
        # 头像
        user_avatar = settings.QINIUYUN_URL + str(house.user.avatar)

        # 返回数据
        house_dict = {
            'hid': house.id,
            'acreage': house.acreage,
            'title': house.title,
            'price': house.price,
            'area_id': house.area_id,
            'address': house.address,
            'room_count': house.room_count,
            'unit': house.unit,
            'capacity': house.capacity,
            'beds': house.beds,
            'deposit': house.deposit,
            'min_days': house.min_days,
            'max_days': house.max_days,
            'facilities': facility_list,
            'comments': comments,
            'img_urls': img_urls,
            'user_avatar': user_avatar,
            'user_id': house.user.id,
            'user_name': house.user.username
        }

        data = {
            'user_id': user_id,
            'house': house_dict
        }
        return JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': data})
